package com.jingdong.callback;

import com.jingdong.callback.model.ConnectivityResult;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.*;

/**
 * 连通性测试工具
 * 
 * @author SDK Team
 */
public class ConnectivityTester {
    
    private static final Logger logger = LoggerFactory.getLogger(ConnectivityTester.class);
    
    /**
     * 测试连通性
     * 
     * @param url 目标URL
     * @return 连通性测试结果
     */
    public static ConnectivityResult test(String url) {
        ConnectivityResult result = new ConnectivityResult();
        
        try {
            URL targetUrl = new URL(url);
            String host = targetUrl.getHost();
            int port = targetUrl.getPort();
            if (port == -1) {
                port = targetUrl.getDefaultPort();
            }
            
            // DNS解析测试
            result.setDns(testDns(host));
            
            // 端口连通性测试
            result.setPort(testPort(host, port));
            
            // HTTP请求测试
            result.setHttp(testHttp(url));
            
        } catch (Exception e) {
            logger.error("连通性测试失败: {}", e.getMessage(), e);
            result.setDns(new ConnectivityResult.DnsResult("unknown", "unknown", false));
            result.setPort(new ConnectivityResult.PortResult("unknown", 0, false, e.getMessage()));
            result.setHttp(new ConnectivityResult.HttpResult(false, 0, e.getMessage()));
        }
        
        return result;
    }
    
    /**
     * 测试DNS解析
     */
    private static ConnectivityResult.DnsResult testDns(String host) {
        try {
            InetAddress address = InetAddress.getByName(host);
            String ip = address.getHostAddress();
            boolean success = !ip.equals(host);
            
            logger.info("DNS解析测试 - 主机: {}, IP: {}, 成功: {}", host, ip, success);
            return new ConnectivityResult.DnsResult(host, ip, success);
            
        } catch (UnknownHostException e) {
            logger.error("DNS解析失败 - 主机: {}, 错误: {}", host, e.getMessage());
            return new ConnectivityResult.DnsResult(host, null, false);
        }
    }
    
    /**
     * 测试端口连通性
     */
    private static ConnectivityResult.PortResult testPort(String host, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), 5000);
            logger.info("端口连通性测试 - {}:{}, 成功", host, port);
            return new ConnectivityResult.PortResult(host, port, true, null);
            
        } catch (IOException e) {
            logger.error("端口连通性测试失败 - {}:{}, 错误: {}", host, port, e.getMessage());
            return new ConnectivityResult.PortResult(host, port, false, e.getMessage());
        }
    }
    
    /**
     * 测试HTTP请求
     */
    private static ConnectivityResult.HttpResult testHttp(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpHead httpHead = new HttpHead(url);
            httpHead.setHeader("User-Agent", "JingdongCallbackSDK-ConnectivityTest/1.0.0");
            
            try (CloseableHttpResponse response = httpClient.execute(httpHead)) {
                int statusCode = response.getStatusLine().getStatusCode();
                boolean success = statusCode >= 200 && statusCode < 400;
                
                logger.info("HTTP请求测试 - URL: {}, 状态码: {}, 成功: {}", url, statusCode, success);
                return new ConnectivityResult.HttpResult(success, statusCode, null);
            }
            
        } catch (Exception e) {
            logger.error("HTTP请求测试失败 - URL: {}, 错误: {}", url, e.getMessage());
            return new ConnectivityResult.HttpResult(false, 0, e.getMessage());
        }
    }
}
